package com.campsys.handler;

import com.campsys.core.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import java.net.BindException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理RuntimeException的异常处理方法
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Result> handleRuntimeException(RuntimeException ex, WebRequest request) {
        // 返回自定义的错误响应
        return new ResponseEntity<Result>(Result.error(ex.getMessage()), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity<Result> handleBindException(BindException ex, WebRequest request) {
        // 返回自定义的错误响应
        return new ResponseEntity<Result>(Result.error(ex.getMessage()), HttpStatus.BAD_REQUEST);
    }
}
